# UDP_module/udp_server.py

from PySide6.QtCore import QCoreApplication, QByteArray
from PySide6.QtNetwork import QUdpSocket, QHostAddress
import datetime
from Infrastructure_Layer import Processor_Interface

class UDPServer:
    def __init__(self, app, data_updated_signal):
        self.app = app
        self.udpSocket = QUdpSocket(app)
        self.udpSocket.bind(QHostAddress.AnyIPv4, 777)
        self.udpSocket.readyRead.connect(self.handleReadyRead)
        self.count = 0
        self.data_updated_signal = data_updated_signal

    def handleReadyRead(self):
        global count
        while self.udpSocket.hasPendingDatagrams():
            datagramSize = self.udpSocket.pendingDatagramSize()
            data, host, port = self.udpSocket.readDatagram(datagramSize)
            current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

            decoded_data = data.data().decode()
            print(f"[{current_time}] Received: {decoded_data} from {host.toString()}:{port}")

            # 发送信号通知 UI 更新
            #self.data_updated_signal.emit(decoded_data)
            self.count += 1
            #对UDP中的数据进行处理
            processdone=Processor_Interface(decoded_data)
            self.data_updated_signal.emit(processdone)
"""
            # 向客户端发送回应
            response = f"Echo: {decoded_data} Count: {self.count}"
            print(f"Count: {self.count}")
            self.udpSocket.writeDatagram(response.encode(), host, port)
"""

            # 更新计数器
            #self.count += 1